package liuliu.throughwaring.ui.activity;

import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import net.tsz.afinal.annotation.view.CodeNote;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import liuliu.custom.control.dialog.LLDialog;
import liuliu.custom.method.Utils;
import liuliu.throughwaring.R;
import liuliu.throughwaring.adapter.CommonAdapter;
import liuliu.throughwaring.adapter.ViewHolder;
import liuliu.throughwaring.base.BaseActivity;
import liuliu.throughwaring.control.main.IMainView;
import liuliu.throughwaring.control.main.MainListener;
import liuliu.throughwaring.model.ChangeItemModel;
import liuliu.custom.model.CodeModel;
import liuliu.throughwaring.model.ItemModel;
import liuliu.throughwaring.model.PoliceModel;
import liuliu.throughwaring.service.NoticeHandlerService;
import liuliu.throughwaring.ui.fragment.ShouYeFragment;
import liuliu.throughwaring.ui.fragment.WodeFragment;

/**
 * 主页
 * 作者：柳伟杰 on 2016/3/14 11:47
 * 邮箱：1031066280@qq.com
 */
public class MainActivity extends BaseActivity implements IMainView {
    public static MainActivity mIntails;
    @CodeNote(id = R.id.shouye_main_ll, click = "onClick")
    LinearLayout shouye_ll;
    @CodeNote(id = R.id.shouye_main_iv)
    ImageView shouye_iv;
    @CodeNote(id = R.id.shouye_main_tv)
    TextView shouye_tv;
    @CodeNote(id = R.id.wode_main_ll, click = "onClick")
    LinearLayout wode_ll;
    @CodeNote(id = R.id.wode_main_iv)
    ImageView wode_iv;
    @CodeNote(id = R.id.wode_main_tv)
    TextView wode_tv;
    @CodeNote(id = R.id.help_main_rl, click = "onClick")
    RelativeLayout help_rl;
    List<ChangeItemModel> listbtn;//生成的按钮集合（需要颜色改变的view）
    int mClick;//被点击的项
    ShouYeFragment shouye;
    WodeFragment wode;
    List<ItemModel> mItems;
    List<CodeModel> mCodeListNative;
    private PopupWindow nearby_people_pop;
    private int tagHeight;//状态栏高度
    private MainListener listener;
    public List<CodeModel> codeList = null;
    private LLDialog llDialog;

    @Override
    public void initViews() {
        setContentView(R.layout.activity_main);
        listener = new MainListener(this, this);
        listbtn = new ArrayList<>();
        mItems = new ArrayList<>();
        mIntails = this;
        Intent intent = new Intent(MainActivity.this, NoticeHandlerService.class);
        startService(intent);
        mCodeListNative = finalDb.findAllByWhere(CodeModel.class, "codeName='Code_Native'");
        llDialog = new LLDialog(this);
    }

    @Override
    public void initEvents() {
        codeList = finalDb.findAllByWhere(CodeModel.class, "codeName='Code_Area'");
        mItems.add(new ItemModel("首页", R.mipmap.shouye_menu_pressed, R.mipmap.shouye_normal));
        mItems.add(new ItemModel("个人中心", R.mipmap.geren_menu_pressed, R.mipmap.geren_normal));
        listbtn.add(new ChangeItemModel(shouye_tv, shouye_iv));//添加组件到listview
        listbtn.add(new ChangeItemModel(wode_tv, wode_iv));//添加组件到listview
        setItem(0);
        mClick = 0;
    }

    private void initPop(View v, List<PoliceModel> list) {
        Rect frame = new Rect();
        getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        tagHeight = frame.top;
        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.pop_neraly_police, null);
        ListView listView = (ListView) view.findViewById(R.id.pop_police_lv);
        TextView popmes = (TextView) view.findViewById(R.id.pop_mes);
        TextView ll = (TextView) view.findViewById(R.id.pop_110);
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:110"));
                startActivity(intent);
            }
        });
        view.findViewById(R.id.pop_cancle_iv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (nearby_people_pop != null) {
                    nearby_people_pop.dismiss();
                }
            }
        });
        nearby_people_pop = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        nearby_people_pop.setAnimationStyle(R.style.pop_main_bottom_anim_style);
        nearby_people_pop.setFocusable(true);
        nearby_people_pop.setOutsideTouchable(true);
        nearby_people_pop.setBackgroundDrawable(new BitmapDrawable());
        nearby_people_pop.showAtLocation(v, Gravity.TOP, 0, tagHeight);
        if (null == list) {
            popmes.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
        } else {
            listView.setAdapter(new CommonAdapter<PoliceModel>(this, list, R.layout.item_help_police) {
                @Override
                public void convert(final ViewHolder holder, final PoliceModel model, int position) {
                    holder.setText(R.id.help_name, model.getPoliceName());
                    holder.setText(R.id.help_content, getCodeVlaue(codeList, model.getPoliceArea()));
                    float juli = Float.parseFloat(model.getPoliceComment()) / 1000;
                    //float num = (float) (Math.round(juli * 1000) / 1000);
                    DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
                    String p = decimalFormat.format(juli);
                    holder.setText(R.id.help_juli, p);
                    holder.setOnClickListener(R.id.edit_btn_congye, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //拨打电话
                            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + model.getPolicePhoneNumber()));
                            startActivity(intent);
                            holder.setBackgroundRes(R.id.edit_btn_congye, R.mipmap.iconfont_call_normal);
                            holder.setEnabled(R.id.edit_btn_congye, false);
                        }
                    });

                }
            });
        }
    }


    /**
     * 底部菜单点击
     *
     * @param position 点击的具体项
     */
    private void setItem(int position) {
        //恢复成未点击状态
        listbtn.get(mClick).getTv().setTextColor(mIntails.getResources().getColor(R.color.main_item_normal));
        Bitmap bitmap = Utils.readBitMap(mIntails, mItems.get(mClick).getNormal_img());
        listbtn.get(mClick).getIv().setImageBitmap(bitmap);
        //设置为点击状态
        listbtn.get(position).getTv().setTextColor(mIntails.getResources().getColor(R.color.main_item_pressed));
        listbtn.get(position).getIv().setImageBitmap(Utils.readBitMap(mIntails, mItems.get(position).getPressed_img()));
        mClick = position;
        // 开启一个Fragment事务
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        hideFragments(transaction);

        switch (position) {
            case 0://首页
                if (shouye == null) {
                    shouye = new ShouYeFragment();
                    transaction.add(R.id.frag_main, shouye);
                } else {
                    transaction.show(shouye);
                }
                break;
            case 1:
                if (wode == null) {
                    wode = new WodeFragment();
                    transaction.add(R.id.frag_main, wode);
                } else {
                    transaction.show(wode);
                }
                break;
        }
        transaction.commit();
    }

    /**
     * 将所有的Fragment都置为隐藏状态。
     *
     * @param transaction 用于对Fragment执行操作的事务
     */
    private void hideFragments(FragmentTransaction transaction) {
        if (shouye != null) {
            transaction.hide(shouye);
        }
        if (wode != null) {
            transaction.hide(wode);
        }
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.shouye_main_ll:
                setItem(0);
                break;
            case R.id.wode_main_ll:
                setItem(1);
                break;
            case R.id.help_main_rl:
                // initPop(help_rl);
                listener.getHelpPolice();
                break;
        }
    }

    @Override
    public void onMainRefreshResult(boolean isTrue, List<PoliceModel> list) {
        if (isTrue) {

        } else {
            Utils.ToastShort(MainActivity.this, "加载失败!");

        }
        initPop(help_rl, list);
    }

    public String getCodeVlaue(List<CodeModel> list, String name) {
        for (CodeModel c : list) {
            if (c.getName().equals(name)) {
                return c.getValue();
            }
        }
        return "";
    }

    /**
     * 点击返回弹出消息框，确定后完全退出系统
     *
     * @param keyCode key的编码
     * @param event   key的时间
     * @return
     * @author cc 2016年4月8日 14:45:14
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            llDialog.setMiddleMessage("确认要退出系统？");
            llDialog.setOnPositiveListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {//点击确定按钮
                    llDialog.cancel();
                    mIntails.finish();//完全退出系统
                    Intent intent = new Intent(MainActivity.mIntails, NoticeHandlerService.class);
                    MainActivity.mIntails.stopService(intent);
                }
            });
            llDialog.setOnNegativeListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    llDialog.cancel();
                }
            });//点击取消按钮
            llDialog.show();
        }
        return false;
    }
}
